from sqlalchemy.ext.asyncio import AsyncSession as Session
from app.schemas.waveup.swap_record import SwapRecordCreate, SwapRecordUpdate
from app.models.waveup.swap_record import SwapRecord
from sqlalchemy import select
from app.schemas.waveup.swap_record import SwapRecordOut
from fastapi import HTTPException

async def create_swap_record(
    session: Session, swap_record_in: SwapRecordCreate
) -> SwapRecord:
    """创建新兑换记录"""
    db_swap_record = SwapRecord.model_validate(swap_record_in)
    session.add(db_swap_record)
    await session.commit()
    await session.refresh(db_swap_record)
    return db_swap_record

async def get_record_by_uid(
    session: Session,
    uid: int,
    pageNo: int = 1,
    pageSize: int = 20,
):
    """查询WaveUp兑换记录列表"""
    statement = select(SwapRecord).where(SwapRecord.uid == uid)
    # 计算总数
    total = await session.execute(statement)
    total = len(total.scalars().all())

    # 分页查询
    statement = statement.offset((pageNo - 1) * pageSize).limit(pageSize)
    result = await session.execute(statement)

    return {
        "records": [SwapRecordOut.model_validate(swap_record) for swap_record in result.scalars().all()],
        "total": total,
        "pageNo": pageNo,
        "pageSize": pageSize
    }

async def update_swap_record(
    session: Session, swap_record_in: SwapRecordUpdate
) -> SwapRecord:
    """更新兑换记录"""
    db_swap_record = await session.get(SwapRecord, swap_record_in.id)
    if not db_swap_record:
        raise HTTPException(status_code=404, detail="兑换记录不存在")
    swap_record_data = swap_record_in.model_dump(exclude_unset=True)
    for key, value in swap_record_data.items():
        setattr(db_swap_record, key, value)
    session.add(db_swap_record)
    await session.commit()
    await session.refresh(db_swap_record)
    return db_swap_record

async def get_record_order_no(
    session: Session,
    order_no: str,
):
    """根据订单号查询兑换记录"""
    statement = select(SwapRecord).where(SwapRecord.swapOrderNo == order_no)
    result = await session.execute(statement)
    return result.scalar_one_or_none()